class WebSocketClient {
    constructor() {
        this.ws = null;
        this.messageHandlers = [];
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectTimeout = 3000;
        this.path = null;
    }

    /**
     * 连接WebSocket
     * @param {string} path WebSocket路径，例如：'/ws/consultation/123'
     */
    connect(path) {
        try {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = `${protocol}//localhost:8080${path}`;
            
            // 创建WebSocket实例
            const ws = new WebSocket(wsUrl);

            // 设置事件处理器
            ws.onopen = () => {
                console.log('WebSocket connected');
                this.reconnectAttempts = 0;
            };

            ws.onmessage = (event) => {
                try {
                    const message = JSON.parse(event.data);
                    this.messageHandlers.forEach(handler => handler(message));
                } catch (error) {
                    console.error('Failed to parse WebSocket message:', error);
                }
            };

            ws.onclose = () => {
                console.log('WebSocket disconnected');
                this.ws = null;
                if (this.reconnectAttempts < this.maxReconnectAttempts) {
                    setTimeout(() => {
                        this.reconnectAttempts++;
                        this.connect(path);
                    }, 1000 * Math.pow(2, this.reconnectAttempts));
                }
            };

            ws.onerror = (error) => {
                console.error('WebSocket error:', error);
            };

            // 保存WebSocket实例
            this.ws = ws;
            this.path = path;
        } catch (error) {
            console.error('Failed to create WebSocket connection:', error);
            throw error;
        }
    }

    sendMessage(message) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify(message));
        } else {
            console.error('WebSocket is not connected');
        }
    }

    addMessageHandler(handler) {
        this.messageHandlers.push(handler);
    }

    removeMessageHandler(handler) {
        const index = this.messageHandlers.indexOf(handler);
        if (index !== -1) {
            this.messageHandlers.splice(index, 1);
        }
    }

    disconnect() {
        if (this.ws) {
            this.ws.close();
            this.ws = null;
        }
        this.messageHandlers = [];
        this.path = null;
    }
}

// 导出WebSocket类而不是实例，让使用者自己创建实例
export default WebSocketClient; 